package com.ciwong.epaper.modules.evaluate.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.TrafficStats;
import android.os.Handler;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.common.CheckIsExamForDetail;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.bean.SentenceAnswer;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.epaper.util.RepeatKeyUtil;
import com.ciwong.epaper.modules.evaluate.bean.SentenceAnswerBean;
import com.ciwong.epaper.modules.evaluate.bean.SubmitResult;
import com.ciwong.epaper.modules.me.bean.MyWork;
import com.ciwong.epaper.modules.me.bean.RequirementContent;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.AddPointTypes;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.modules.share.QQShareHelper;
import com.ciwong.epaper.modules.share.QQShareListener;
import com.ciwong.epaper.modules.share.WxShareHelper;
import com.ciwong.epaper.modules.share.WxShareListener;
import com.ciwong.epaper.modules.share.bean.ShareMsgObj;
import com.ciwong.epaper.service.UploadeFailService;
import com.ciwong.epaper.util.Base64Utils;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.epaper.widget.SubmitSuccessfulResultPage;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.widget.BuyServiceDialog;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.UiError;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by dylan on 2017/4/25.
 */
public class SentenceResultActivity extends BaseActivity implements View.OnClickListener {

    private Context mContext = this;

    public static Integer SENTENCE_STATE_SUE = 5;

    public static Integer SENTENCE_STATE_FAIL = 3;

    public static Integer SENTENCE_STATE_DEF = 1;

    private ArrayList<SentenceAnswerBean> resultAnsers;
    private String workId;
    private String packageId;
    private String cId;
    private int moduleId;
    private String versionId;
    private String resourceName;
    private String parentVersionId;
    private String resourceType;
    private int contentId;
    /**
     * 服务id
     */
    private int workType;
    private float workScore;
    private Integer isUploadFail;
    private String doWrokId;
    private String classId;
    private long returnWorkLong;

    protected int typeMode;
    DownLoadInfo mDownLoadInfo;
    Module mModule;
    int position;

    //界面相关
    private ImageView img_upload_state;
    private SubmitSuccessfulResultPage score_result_page;
    private View result_lay;//结果
    private View handle_state_upload_ing;
    private SeekBar seek_bar_make_score;
    private Button btn_retry_commit;
    private TextView tx_upload_progress;
    private TextView tx_low_net_speed_tips;
    private ImageView iv_close_page;

    private ImageView wechat, wechatFriend, qq, qqFriend;//分享

    //提交状态
    private final int RESULT_STATE_UPLOADING = 0; //提交
    private final int RESULT_STATE_EVALUATE_SUCCESS = 2; //提交成功
    private final int RESULT_STATE_UPLOAD_FAIL = -1; //提交失败

    //要提交的数据
    private SentenceAnswer sentenceAnswer;

    Handler handler;

    private float mTotalScore = 100;

    private boolean is_sutdown = false;//是否强制关闭提交页面

    //无网时提示信息
    public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";

    /**
     * 是否提交成功
     */
    private boolean isSubmit = false;

    private long startTime;

    private boolean isFail;

    private boolean isClose = true;

    private boolean isUpdataFail = false;

    private String mUuid;

    private WorkContents mWorkContents;
    protected RequirementContent requirementContent;

    private long nowTime = 0;

    //查看类型
    private int showScoreMode;

    private int prog = 0;//上传完成数量，　　只是计数成功的次数　
    private int max = 0;

    //本地作业列表
    private List<MyWork> mLocalWorkList;

    //截止时间
    private long effectiveDate = -1;

    private EApplication application;

    /**
     * 默认服务包剩余使用时间
     */
    public boolean serviceExpired;

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(CONNECTIVITY_CHANGE_ACTION)) {
                if (!NetworkUtils.isOnline()) {
                    if (result_lay.getVisibility() != View.VISIBLE) {
                        updateStateImg(RESULT_STATE_UPLOAD_FAIL, 0);
                    }
                }
            }
        }
    };

    @Override
    protected void preCreate() {
        super.preCreate();
        TAG = "retryscore2";
        Intent intent = getIntent();
        isUploadFail = intent.getIntExtra(IntentFlag.INTENT_FLAG_UPLOAD_FAIL, SENTENCE_STATE_DEF);
        //将答案从缓存取出
        Gson gson = new Gson();
        String sharedString = CWSys.getSharedString(BaseConstants.SHARE_KEY_SENTENCE_ANSWER);
        if (null != sharedString && !"".equals(sharedString)) {
            resultAnsers = gson.fromJson(sharedString, new TypeToken<ArrayList<SentenceAnswerBean>>() {
            }.getType());
        } else {
            resultAnsers = new ArrayList<>();
        }
        workId = intent.getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);
        mDownLoadInfo = (DownLoadInfo) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
        mModule = (Module) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        classId = intent.getStringExtra(IntentFlag.INTENT_FLAG_CLASS_ID);
        effectiveDate = getIntent().getLongExtra(IntentFlag.INTENT_FLAG_WORK_EFFECTIV_TIME, -1);

        requirementContent = (RequirementContent) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_REQU_CONTENT);

        if (mDownLoadInfo != null) {
            packageId = mDownLoadInfo.getBookId();
            cId = mDownLoadInfo.getChapterId();


            if (mDownLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
                moduleId = Integer.valueOf(mDownLoadInfo.getModuleId());
                versionId = mDownLoadInfo.getVersionId();
                resourceName = mDownLoadInfo.getResourceName();
                parentVersionId = "0";
                resourceType = mDownLoadInfo.getResourceType();

            } else {
                moduleId = mModule.getModuleInfo().getModuleId();
                position = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
                if (mModule.getResourceList() != null) {
                    ModuleContent moduleContent = mModule.getResourceList().get(position);
                    if (moduleContent != null) {
                        versionId = moduleContent.getVersionId();
                        resourceName = moduleContent.getResourceName();
                        parentVersionId = moduleContent.getParentVersionId();
                        resourceType = moduleContent.getResourceType();
                    }
                }
            }
        }
        workType = intent.getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);

        contentId = intent.getIntExtra(IntentFlag.INTENT_FLAG_CONTENTID, 0);

        mWorkContents = (WorkContents) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_WORK_CONTENTS);
        workScore = 100;

        typeMode = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_TYPE, SpeechPlayController.LISTENER_MODE_ZHUJU);

        startTime = CWSys.getSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, workId), 0);
        if (startTime == 0) {
            startTime = mDownLoadInfo.getStartTime();
        }

        mUuid = CWSys.getSharedString(RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, workId, typeMode), null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        WxShareHelper.getInstance().onResumeResultData();
    }

    @Override
    protected int setView() {
        return R.layout.listen_speak_result;
    }

    @Override
    protected void initEvent() {

        try {
            iv_close_page.setOnClickListener(this);
            btn_retry_commit.setOnClickListener(this);
            wechat.setOnClickListener(new ViewOnClickListener() {//微信分享
                @Override
                public void avertRepeatOnClick(View v) {
                    weChatShare(1);

                }
            });

            wechatFriend.setOnClickListener(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    weChatShare(2);
                }

            });

            qq.setOnClickListener(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    qqShare("QQ");
                }
            });

            qqFriend.setOnClickListener(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    qqShare("QZone");
                }
            });

        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }

    /**
     * "QQ"代表分享给QQ好友，"QZone"代表分享到QQ空间
     *
     * @param qq
     */
    private void qqShare(String qq) {
        try {
            ShareMsgObj shareMsgObj = new ShareMsgObj();
            shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);
            shareMsgObj.setLocalImgUrl(FileUtil.getShareWordIconLocalPath(getApplicationContext()));
            shareMsgObj.setUrl(getShareBase64Url());
            String score = getString(R.string.speech_word_score, MeUtil.formatScore(sentenceAnswer.getActualScore()));
            String shareContent = getString(R.string.str_share_contentword, score);
            shareMsgObj.setMsgDesription(shareContent);
            if (qq.equals("QQ")) {
                shareMsgObj.setMsgTitle(resourceName);
                QQShareHelper.getInstance().shareToQQ(SentenceResultActivity.this, shareMsgObj, new QQShareListener() {
                    @Override
                    public void onQQShareSucc(Object var) {
                        shareAddPointType(doWrokId, AddPointTypes.SHERE_SCORE);
                    }

                    @Override
                    public void onQQShareFailure(UiError var1) {
                    }

                    @Override
                    public boolean onQQShareCancel() {
                        return false;
                    }
                });
            } else if (qq.equals("QZone")) {
                shareMsgObj.setMsgTitle(shareContent);
                shareMsgObj.setImg_url(FileUtil.getShareWordIconLocalPath(getApplicationContext()));
                QQShareHelper.getInstance().shareToQZone(SentenceResultActivity.this, shareMsgObj, new QQShareListener() {
                    @Override
                    public void onQQShareSucc(Object var) {
                        shareAddPointType(doWrokId, AddPointTypes.SHERE_SCORE);
                    }

                    @Override
                    public void onQQShareFailure(UiError var1) {

                    }

                    @Override
                    public boolean onQQShareCancel() {

                        return false;
                    }
                });
            }

        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /**
     * 1代表分享给好友，2代表分享到朋友圈
     *
     * @param wxType
     */
    private void weChatShare(int wxType) {
        try {
            WxShareHelper.getInstance().initWxShare(SentenceResultActivity.this, new WxShareListener() {
                @Override
                public void onWxShareing(String str) {
                }

                @Override
                public void onWxShareSucc(String var) {
                    shareAddPointType(doWrokId, AddPointTypes.SHERE_SCORE);
                }

                @Override
                public void onWxShareFailure(int var, String var1) {
                    Log.d("sharetest", "##########onWxShareFailure######" + var1);
                }

                @Override
                public boolean onWxShareCancel() {
                    return false;
                }
            });

            ShareMsgObj shareMsgObj = new ShareMsgObj();
            shareMsgObj.setWxType(wxType);
            shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.word_share_icon);
            shareMsgObj.setThunbBmp(bmp);

            shareMsgObj.setUrl(getShareBase64Url());
            String score = getString(R.string.speech_word_score, MeUtil.formatScore(sentenceAnswer.getActualScore()));
            String shareContent = getString(R.string.str_share_contentword, score);
            if (wxType == 1) {
                shareMsgObj.setMsgDesription(shareContent);
                shareMsgObj.setMsgTitle(resourceName);
            } else if (wxType == 2) {
                shareMsgObj.setMsgTitle(shareContent);
            }
            WxShareHelper.getInstance().sendReq(shareMsgObj);
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    private void shareAddPointType(String doWorkId, String type) {
        MeDao.getInstance().addPoint(EApplication.getInstance().getUserInfoBase().getUserId() + "", EApplication.getInstance().getUserInfoBase().getRealName(), type, doWorkId);
    }

    //得到加密后的URL
    public String getShareBase64Url() {
        String shareUrl = EpaperConstant.URL_READING_REPEAD;
        StringBuffer sb1 = new StringBuffer(shareUrl);
        StringBuffer sb = new StringBuffer();
        sb.append("pageType=4");
        sb.append("&clientId=");
        sb.append(EConstants.CLIENT_ID);
        long useeId = getUserInfoBase().getUserId();
        sb.append("&userId=");
        sb.append(useeId);
        sb.append("&brandId=");
        sb.append(EApplication.BRAND_ID);
        sb.append("&versionId=");
        sb.append(versionId);
        sb.append("&parentVersionId=");
        sb.append(parentVersionId);
        sb.append("&doWorkId=");
        sb.append(doWrokId);
        String param = Base64Utils.getBase64(sb.toString());
        shareUrl = sb1.append(param).toString();
        return shareUrl;
    }


    @Override
    protected void init() {
        handler = new Handler();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CONNECTIVITY_CHANGE_ACTION);
        registerReceiver(broadcastReceiver, intentFilter);
        application = (EApplication) getApplication();
        if (application != null) {
            //服务是否过期
            serviceExpired = application.isServiceExpired();
        }
        if (!serviceExpired) {
            if (mWorkContents != null && mWorkContents.getIsFree() == 1) {
                serviceExpired = true;
            }
        }
        setTitleText(resourceName);
        setBackImg(R.mipmap.icon_x_exit);

        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                showDailog();
            }
        });
        setValideSource(false);

        if (EConstants.IS_YOUKE) {
            //do  nothing
        } else {
            if (isUploadFail.equals(SENTENCE_STATE_FAIL)) {
                //说明上次提交是失败的那么这次还要继续提示从新提交  提交失败
                updateStateImg(RESULT_STATE_UPLOAD_FAIL, 0);
            } else {
                //继续提交作业
                updateStateImg(RESULT_STATE_UPLOADING, 0);//ui的刷新
                showUploadText();
                submitJson();
            }
        }
        if (EConstants.QQ_APP_ID.equals("") || null == EConstants.QQ_APP_ID) {
            qq.setImageResource(R.mipmap.share_qq_unstalled);
            qqFriend.setImageResource(R.mipmap.share_qq_space_unstalled);
            qq.setEnabled(false);
            qqFriend.setEnabled(false);
        }
    }


    private void showUploadText() {
        //总大小
        long remainUploadSize = getRemainUploadFileSize();

        long speed = getNetSpeed();
        Log.d(TAG, "######## speed#####" + speed);

        long remainSecods = 0;
        if (speed > 0) {
            remainSecods = remainUploadSize / speed;
        } else {
            //如果网速为0 当做1kb
            remainSecods = remainUploadSize;
        }
        tx_upload_progress.setVisibility(View.VISIBLE);


        tx_upload_progress.setText(ListenSpeakUtil.formatNetSpeed(SentenceResultActivity.this, (int) speed, (int) remainSecods, true));
        if (result_lay.getVisibility() != View.VISIBLE && isClose && !isFail) {
            //说明提交还没完成
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "######## handler.postDelayed#####");
                    showUploadText();
                }
            }, 1000);
        }
    }


    /**
     * 获取未下载文件的大小
     *
     * @return
     */
    private long getRemainUploadFileSize() {
        long remainSize = 0;
        for (int i = 0; i < resultAnsers.size(); i++) {
            if (resultAnsers.get(i).getUrlLiYun() == null || resultAnsers.get(i).getUrlLiYun().equals("")) {
                File file = new File(resultAnsers.get(i).getSoundUrl());
                if (file.exists()) {
                    remainSize = remainSize + file.length();
                }
            }
        }
        return remainSize / 1024;
    }

    //获取通过Mobile连接收到的字节总数
    private long lastTotalRxBytes = 0;
    private long lastTimeStamp = 0;


    /**
     * 得到当前网速
     *
     * @return
     */
    private long getNetSpeed() {

        long nowTotalRxBytes = getTotalRxBytes();//计算上行速度
        long nowTimeStamp = System.currentTimeMillis();
        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换
        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;
        if (speed < 3) {
            Random rand = new Random();
            speed = rand.nextInt(3);
        }
        return speed;
    }


    private long getTotalRxBytes() {
        return TrafficStats.getUidRxBytes(getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
    }


    @Override
    protected void loadData() {

    }

    @Override
    protected void findViews() {
        //重新提交
        img_upload_state = (ImageView) findViewById(R.id.img_upload_state);
        handle_state_upload_ing = findViewById(R.id.handle_state_upload_ing);
        seek_bar_make_score = (SeekBar) findViewById(R.id.seek_bar_make_score);
        btn_retry_commit = (Button) findViewById(R.id.btn_retry_commit);
        tx_upload_progress = (TextView) findViewById(R.id.tx_upload_progress);
        tx_low_net_speed_tips = (TextView) findViewById(R.id.tx_low_net_speed_tips);
        score_result_page = findViewById(R.id.score_result_page);
        result_lay = findViewById(R.id.result_lay);
        iv_close_page = (ImageView) score_result_page.findViewById(R.id.iv_close_page);

        //分享
        wechat = (ImageView) score_result_page.findViewById(R.id.share_weixin);
        wechatFriend = (ImageView) score_result_page.findViewById(R.id.share_weixin_friend);
        qq = (ImageView) score_result_page.findViewById(R.id.share_qq);
        qqFriend = (ImageView) score_result_page.findViewById(R.id.share_qq_space);
    }

    @Override
    protected void onDestroy() {
        SpeechPlayController.readCount = 0;
        isClose = false;

        checkData();
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
        super.onDestroy();
    }

    /**
     * 检查数据如果没有上传成功则保留在本地下次可以取
     */
    private void checkData() {
        //只要提交没有成功就保持这个状态
        if (!isSubmit) {
            if (resultAnsers.size() > 0) {
                //保持在本地
                onSaveSatate(SENTENCE_STATE_FAIL);
                //                    onSaveSentenceRecord(sentenceAnswer);
            }
        } else {
            if (resultAnsers.size() > 0) {
                //保持在本地
                onSaveSentenceRecord(null);
                onSaveSatate(SENTENCE_STATE_SUE);
            }
        }
    }

    @Override
    protected void onPause() {
        //        checkData();
        super.onPause();
    }

    /**
     * 提交成功更新本地的缓存
     */
    private void updataIsUpload() {
        //当进来是失败的情况下更新 其他情况下不需要更新
        if (resultAnsers != null && resultAnsers.size() > 0) {
            onSaveSentenceRecord(null);
            onSaveSatate(SENTENCE_STATE_SUE);
        }
    }


    /**
     * 检查是否有没有上传成功的句子没有上传成功则继续上传
     */
    private void submitJson() {//提交答案数据
        //到这里表示已经全部
        if (!isSubmit) {
            submit();
        } else {
            if (sentenceAnswer != null) {
                updataIsUpload();
                updateStateImg(RESULT_STATE_EVALUATE_SUCCESS, Math.round(sentenceAnswer.getActualScore()));
            }
        }

    }

    private void submit() {//提交Json
        if (isUpdataFail) {
            return;
        }
        CWLog.d("aliyun", "提交" + System.currentTimeMillis() + "tag===json");
        String uuid = CWSys.getSharedString(RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, workId, typeMode), null);
        Log.d(TAG, "#######submit() 提交作业 uuid#########" + uuid);
        if (null == uuid) {
            //有可能提交成功清除uuid后再结果页面停留或者用清理软件销毁当前页面，重新生成页面后 uuid 没有
            onSaveSentenceRecord(null);
            onSaveSatate(SENTENCE_STATE_SUE);
            finish();
            return;
        }

        final String dataJson = toJson(uuid);

        EpaperDao.getInstance().submitReadWork(dataJson, 0, sentenceAnswer.getWorkId(), sentenceAnswer.getContentId(), new BaseExtCallBack(this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

            @Override
            public void success(Object data) {
                CWLog.d("aliyun", "提交json成功" + System.currentTimeMillis() + "tag===json");
                SubmitResult submitResult = (SubmitResult) data;
                if (null != submitResult) {
                    doWrokId = submitResult.getDoWorkId();
                    returnWorkLong = submitResult.getWorkLong();
                }
                commitSuccess();

            }

            @Override
            public void failed(Object data) {
                CWLog.d("aliyun", "提交json失败" + System.currentTimeMillis() + "tag===json");
                updateStateImg(RESULT_STATE_UPLOAD_FAIL, 0);
                if (null != data) {
                    FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_SENTENCE_SPEECH, data.toString(), dataJson, "句子提交作业失败：" + getUrl());
                    Log.d(TAG, "#######submit() 提交作业 failed#########" + data.toString());
                }

            }

            @Override
            public void failed(int errorCode, Object data) {
                CWLog.d("aliyun", "提交json失败" + System.currentTimeMillis() + "tag===json");
                updateStateImg(RESULT_STATE_UPLOAD_FAIL, 0);
                super.failed(errorCode, data);
                try {
                    if (errorCode == 105) {
                        commitSuccess();
                    } else {
                        //重复提交
                        if (errorCode == EConstants.ERROR_CODE_REPEAT_COMMIT) {
                            commitSuccess();
                        }
                        if (null != data) {
                            FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_SENTENCE_SPEECH, data.toString(), dataJson, "句子提交作业失败：" + getUrl());
                            Log.d(TAG, "#######submit() 提交作业 errorCode#########" + errorCode);
                            Log.d(TAG, "#######submit() 提交作业 failed#########" + data.toString());
                        }
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }


                //重复提交
                if (errorCode == EConstants.ERROR_CODE_REPEAT_COMMIT) {
                    commitSuccess();
                }
                if (null != data) {
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_SENTENCE_SPEECH, data.toString(), "句子提交作业失败：" + getUrl());
                    Log.d(TAG, "#######submit() 提交作业 errorCode#########" + errorCode);
                    Log.d(TAG, "#######submit() 提交作业 failed#########" + data.toString());
                }
            }
        });
    }


    private void commitSuccess() {

        Intent intent = new Intent();
        intent.putExtra(IntentFlag.INTENT_FLAG_UUID, mUuid);
        intent.putExtra(IntentFlag.INTENT_FLAG_MP3_TYPE, IntentFlag.INTENT_FLAG_MP3_TYPE_SENTENCE);
        intent.putExtra(IntentFlag.INTENT_FLAG_WORK_START_TIME, startTime);
        intent.setAction(IntentFlag.INTENT_FLAG_COMPLATE_ONE_HOMEWORK);
        sendBroadcast(intent);
        //作业提交成功 清除开始时间
        CWSys.setSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, workId), 0);

        isSubmit = true;
        clearRecord();
        Log.d(TAG, "#######submit() 提交作业 success doWrokId#########" + doWrokId);
        sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG));
        sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
        //                if (sentenceAnswer != null)
        {
            updataIsUpload();
            updateStateImg(RESULT_STATE_EVALUATE_SUCCESS, Math.round(sentenceAnswer.getActualScore()));
        }
    }


    private String toJson(String uuid) {


        float sumScore = 0;//总分数
        int countTime = 0;//总时间
        ArrayList<SentenceAnswer.WorkAnswers> workList = new ArrayList<>();
        for (int i = 0; i < resultAnsers.size(); i++) {
            SentenceAnswerBean sentenceAnswerBean = resultAnsers.get(i);
            sumScore = sentenceAnswerBean.getSentence().getScore() + sumScore;
            SentenceAnswer.Answers answers = new SentenceAnswer.Answers(sentenceAnswerBean.getSentence().getText(), sentenceAnswerBean.getUrlLiYun(), sentenceAnswerBean.getReadTimes(),
                    sentenceAnswerBean.getAudioDuration(), sentenceAnswerBean.getLines(), sentenceAnswerBean.getYzsAudioUrl(), sentenceAnswerBean.getFluency(), sentenceAnswerBean.getIntegrity(), sentenceAnswerBean.getPronunciation());
            ArrayList<SentenceAnswer.Answers> anList = new ArrayList<>();
            anList.add(answers);
            SentenceAnswer.WorkAnswers workAnswers = new SentenceAnswer.WorkAnswers(sentenceAnswerBean.getSentence().getTextId(), sentenceAnswerBean.getSentence().getScore(), 4, anList);
            workList.add(workAnswers);
            if (i == (resultAnsers.size() - 1)) {
                countTime = (int) sentenceAnswerBean.getCountTime();
            }
        }
        sumScore = sumScore / resultAnsers.size();
        sentenceAnswer = new SentenceAnswer();
        UserInfoBase userInfo = EApplication.getInstance().getUserInfoBase();
        if (userInfo != null) {
            sentenceAnswer.setUserName(userInfo.getRealName());
        }
        sentenceAnswer.setWorkId(workId);
        sentenceAnswer.setSessionId(uuid);
        sentenceAnswer.setPackageId(packageId);
        sentenceAnswer.setcId(cId);
        sentenceAnswer.setClassId(classId);
        sentenceAnswer.setModuleId(moduleId);
        sentenceAnswer.setResourceName(resourceName);

        if (null != mWorkContents) {
            sentenceAnswer.setParentVersionId(mWorkContents.getParentVersionId());
            sentenceAnswer.setVersionId(mWorkContents.getVersionId());
        } else {
            sentenceAnswer.setParentVersionId(parentVersionId);
            sentenceAnswer.setVersionId(versionId);
        }

        sentenceAnswer.setResourceType(resourceType);
        sentenceAnswer.setWorkLong(countTime / 1000);
        sentenceAnswer.setDoWorkPackageUrl("");
        sentenceAnswer.setActualScore(Math.round(sumScore));
        sentenceAnswer.setBrandId(EApplication.BRAND_ID);
        sentenceAnswer.setWorkType(workType);
        sentenceAnswer.setContentId(contentId);
        sentenceAnswer.setWorkScore(workScore);
        sentenceAnswer.setWorkAnswers(workList);
        sentenceAnswer.setStartTime(startTime);
        return sentenceAnswer.toString();
    }

    private void updateStateImg(int state, final float totalScore) {

        try {

            switch (state) {
                case RESULT_STATE_UPLOADING://提交
                    isUpdataFail = false;

                    if (null != img_upload_state)
                        img_upload_state.setImageResource(R.mipmap.img_upload_state_ing);

                    result_lay.setVisibility(View.GONE);
                    handle_state_upload_ing.setVisibility(View.VISIBLE);
                    btn_retry_commit.setVisibility(View.GONE);

                    try {
                        //作业过来的
                        if (Long.valueOf(workId) > 0) {
                            score_result_page.setRankLinIsVis(View.VISIBLE);
                            score_result_page.setOnToRankListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    String contentId = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_CONTENTID);

                                    MeJumpManager.jumpToRankH5Activity(R.string.go_back, SentenceResultActivity.this, contentId, resourceName);
                                }
                            });
                        } else {
                            //自主学习
                            score_result_page.setRankLinIsVis(View.GONE);
                        }

                    } catch (Exception e) {
                        score_result_page.setRankLinIsVis(View.GONE);
                        e.printStackTrace();
                    }
                    break;
                case RESULT_STATE_EVALUATE_SUCCESS://提交成功
                    Intent intent = new Intent();
                    intent.putExtra(IntentFlag.INTENT_FLAG_UUID, mUuid);
                    intent.putExtra(IntentFlag.INTENT_FLAG_MP3_TYPE, IntentFlag.INTENT_FLAG_MP3_TYPE_SENTENCE);
                    intent.putExtra(IntentFlag.INTENT_FLAG_WORK_START_TIME, startTime);
                    intent.setAction(IntentFlag.INTENT_FLAG_COMPLATE_ONE_HOMEWORK);
                    sendBroadcast(intent);
                    isUpdataFail = false;
                    img_upload_state.setImageResource(R.mipmap.img_upload_state_success);
                    handle_state_upload_ing.setVisibility(View.GONE);
                    btn_retry_commit.setVisibility(View.GONE);
                    final String score = getString(R.string.speech_word_score, MeUtil.formatScore(totalScore));

                    hideTitleBar();
                    result_lay.setVisibility(View.VISIBLE);
                    score_result_page.setToalScore(100);

                    if (null != mWorkContents) {
                        nowTime = mWorkContents.getNowDate();
                        // 查看类型：0 提交立马能查看，1截止时间到后查看
                        showScoreMode = mWorkContents.getShowScoreMode();
                    }

                    score_result_page.setEvaluateState(0, true, score, -1, nowTime, effectiveDate, showScoreMode, serviceExpired);
                    //如果返回作业用时失败 则使用旧用时
                    if (returnWorkLong != 0) {
                        score_result_page.setWorkTime(ListenSpeakUtil.formatWorkLong(this, (int) returnWorkLong));
                    } else {
                        score_result_page.setWorkTime(ListenSpeakUtil.formatWorkLong(this, sentenceAnswer.getWorkLong()));
                    }

                    score_result_page.setCountText("句子个数");
                    score_result_page.setScoreText(resultAnsers.size() + "");
                    if (Long.valueOf(workId) > 0) {
                        RequirementContent requirementContent = new Gson().fromJson(mWorkContents.getRequirementContent(),
                                RequirementContent.class);
                        int requireTimes = requirementContent.getReadtimes();
                        //提交成功时加1
                        mWorkContents.setSubmitCount(mWorkContents.getSubmitCount() + 1);
                        int submitCounts = mWorkContents.getSubmitCount();
                        if (submitCounts >= requireTimes) {
                            score_result_page.tv_submit_description.setVisibility(View.INVISIBLE);
                            score_result_page.setSueButText("完    成");
                        } else {
                            score_result_page.tv_submit_description.setVisibility(View.VISIBLE);
                            score_result_page.setSueButText("再次跟读");
                        }
                        String submitDescription = "老师要求读" + requireTimes + "次,已读" + submitCounts + "次";
                        score_result_page.tv_submit_description.setText(score_result_page.wordDyeing("老师要求读" + requireTimes + "次，", "已读" + submitCounts + "次"));
                    } else {
                        score_result_page.setSueButText("完    成");
                    }
                    score_result_page.setTimeTitleText("跟读用时");
                    score_result_page.setTitleText(resourceName);

                    score_result_page.btn_return_last_page.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if ("再次跟读".equals(score_result_page.btn_return_last_page.getText().toString())) {

                                isSubmit = false;

                                EpaperJumpManager.jumpToSentenceRead(R.string.go_back, SentenceResultActivity.this, workId, mDownLoadInfo, mModule, requirementContent,
                                        position, typeMode,
                                        RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, sentenceAnswer.getWorkType(), sentenceAnswer.getClassId(), sentenceAnswer.getContentId(), mWorkContents, effectiveDate);
                                finish();
                           /* if(MainActivity.curFragment instanceof HomeWorkFragment){
                                HomeWorkFragment homeWorkFragment = (HomeWorkFragment) MainActivity.curFragment;
                                homeWorkFragment.gotoListentAndRepeatAgain();
                                finish();
                            }*/


                            } else {
                                Intent intent = new Intent(EpaperConstant.INTENT_BOACK_REF_WORK);
                                intent.putExtra(IntentFlag.INTENT_FLAG_ACTUAL_SCORE, totalScore);
                                intent.putExtra(IntentFlag.INTENT_FLAG_WORK_STATUS, 1);
                                sendBroadcast(intent);
                                finish();
                            }

                            SpeechPlayController.readCount = 0;

                        }
                    });
                    iv_close_page.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SpeechPlayController.readCount = 0;
                            Intent intent = new Intent(EpaperConstant.INTENT_BOACK_REF_WORK);
                            intent.putExtra(IntentFlag.INTENT_FLAG_ACTUAL_SCORE, totalScore);
                            intent.putExtra(IntentFlag.INTENT_FLAG_WORK_STATUS, 1);
                            sendBroadcast(intent);
                            finish();
                        }
                    });
                    score_result_page.setOnCheckDetailListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(SentenceResultActivity.this, contentId + "", 0);
                            if (!orNotWatchDetails)
                                return;
                            if (serviceExpired) {
                                // 直接跳转到新的学习记录页面
                                jumpToStudyRecordH5();
                            } else {
                                setBuyServiceDialog();
                            }
                        }
                    });
                    score_result_page.setOnCheckTipsListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(SentenceResultActivity.this, contentId + "", 0);
                            if (!orNotWatchDetails)
                                return;
                            if (serviceExpired) {
                                // 直接跳转到新的学习记录页面
                                jumpToStudyRecordH5();
                            } else {
                                setBuyServiceDialog();
                            }
                        }
                    });
                    try {
                        //作业过来的
                        if (Long.valueOf(workId) > 0) {
                            score_result_page.setRankLinIsVis(View.VISIBLE);
                            score_result_page.setOnToRankListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    MeJumpManager.jumpToRankH5Activity(R.string.go_back, SentenceResultActivity.this, contentId + "", resourceName);
                                }
                            });
                        } else {
                            //自主学习
                            score_result_page.setRankLinIsVis(View.GONE);
                        }

                    } catch (Exception e) {
                        score_result_page.setRankLinIsVis(View.GONE);
                        e.printStackTrace();
                    }

                    break;

                case RESULT_STATE_UPLOAD_FAIL://提交失败
                    isUpdataFail = true;
                    isFail = true;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            result_lay.setVisibility(View.GONE);
                            handle_state_upload_ing.setVisibility(View.GONE);
                            btn_retry_commit.setVisibility(View.VISIBLE);
                            img_upload_state.setImageResource(R.mipmap.img_upload_state_fail);
                            checkData();
                        }
                    });
                    //score_result_page.setVisibility(View.GONE);
                    break;
            }

        } catch (
                OutOfMemoryError error) {

        }

    }

    /**
     * 直接跳转到新的学习记录页面
     */
    private void jumpToStudyRecordH5() {
        try {
            //直接跳转到新的学习记录页面
            String url = EpaperConstant.URL_READING_REPEAD + "pageType=3";
            StringBuffer sb = new StringBuffer(url);
            sb.append("&clientId=");
            sb.append(EConstants.CLIENT_ID);
            long useeId = getUserInfoBase().getUserId();
            sb.append("&userId=");
            sb.append(useeId);
            sb.append("&brandId=");
            sb.append(EApplication.BRAND_ID);
            sb.append("&versionId=");
            sb.append(versionId);
            sb.append("&parentVersionId=");
            sb.append(parentVersionId);
            sb.append("&doWorkId=");
            sb.append(doWrokId);
            String title;
            try {
                title = java.net.URLEncoder.encode(resourceName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                title = "";
            }
            title = title.replace("+", "%20");
            sb.append("&title=");
            sb.append(title);
            MeJumpManager.jumpToStudyRecordH5Activity(ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT, SentenceResultActivity.this, R.string.go_back, -1, sb.toString(), resourceName, 0);
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    private BuyServiceDialog buyServiceDialog;

    public void setBuyServiceDialog() {
        if (buyServiceDialog == null) {
            buyServiceDialog = new BuyServiceDialog(SentenceResultActivity.this);
            buyServiceDialog.setMenuOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    if (workType > 0) {
                        //购买服务包
                        MeJumpManager.jumpBuyService(SentenceResultActivity.this, R.string.go_back, workType, -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, "");
                    } else {
                        //拓展服务
                        MeJumpManager.jumpToResourseCenterH5Activity(SentenceResultActivity.this, R.string.go_back, getResources().getString(R.string.resource_center));
                    }
                    buyServiceDialog.dismiss();
                }
            });
            buyServiceDialog.setClosOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    buyServiceDialog.dismiss();
                }
            });
        }
        buyServiceDialog.show();
    }

    @Override
    public void onClick(View v) {
        UploadeFailService.startService();
        if ((v.getId() == R.id.btn_retry_commit)) {
            if (EConstants.IS_YOUKE) {
                EConstants.SENTENCE_IS_YOUKE_LOGIN = true;
                NewLoginDialog newLoginDialog = new NewLoginDialog(SentenceResultActivity.this);
                newLoginDialog.showLoginDialog();
            } else {
                if (!NetworkUtils.isOnline()) {
                    Toast toast = Toast.makeText(SentenceResultActivity.this, "网络不可用,请连接网络后重试!", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                    toast.show();
                    return;
                }
                updateStateImg(RESULT_STATE_UPLOADING, 0);
                showUploadText();
                submitJson();
            }


        }
    }


    private void onSaveSatate(int state) {
        String userId = SerializableManager.getInstance().getUserId(true);
        if (userId != null && !userId.equals("") && !userId.equals(",0")) {
            //            String keyTemp=ESystem.getSaveRecordKey(mDownLoadInfo, mModule, position, workId, SerializableManager.SerializeKey.SHARE_KEY_SENTENCE_STATE + typeMode);
            String keyTemp = RepeatKeyUtil.getSaveSentenceRepeatStatueKey(mDownLoadInfo, mModule, position, workId, mUuid);
            SerializableManager.getInstance().serialize(keyTemp, state);
        }
    }

    private void onSaveSentenceRecord(ArrayList<SentenceAnswerBean> answerList) {
        String userId = SerializableManager.getInstance().getUserId(true);
        //           if(userId!=null&&!userId.equals("")&& !userId.equals(",0"))
        {
            String key = RepeatKeyUtil.getSaveRepeatAnswerListKey(mDownLoadInfo, mModule, position, workId, mUuid);
            //               String key = ESystem.getSaveRecordKey(mDownLoadInfo, mModule, position, workId, SerializableManager.SerializeKey.SHARE_KEY_SENTENCE_RECORD + typeMode);
            SerializableManager.getInstance().serialize(key, answerList);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //返回键监听
            showDailog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void showDailog() {
        if (isSubmit) {
            sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG));
            sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
            finish();
        } else {
            CWDialog mDialog = new CWDialog(this);
            // mDialog.setTitle(R.string.lear_title);
            mDialog.setMessage("作业正在提交中，是否确定退出?");
            mDialog.setPositiveButton(android.R.string.cancel, null);
            mDialog.setNegativeButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            finish();

                        }
                    });
            // }
            mDialog.show();
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_QQ_SHARE || requestCode == Constants.REQUEST_QZONE_SHARE) {
            QQShareHelper.getInstance().onActivityResultData(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 清除记录
     */
    private void clearRecord() {
        //        清除本次做作业或自主练习活动key,只有活动key 清
        CWSys.setSharedString(RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, workId, typeMode), null);
        //        String key = ESystem.getSaveRecordKey(mDownLoadInfo, mModule, position, workId, SerializableManager.SerializeKey.SHARE_KEY_SENTENCE_RECORD + typeMode);
        //        CWSys.setSharedString(key, null);
    }

}
